import * as THREE from '../../build/three.module.js';
import { GUI } from '../../jsm/libs/dat.gui.module.js';
import { OrbitControls } from '../../jsm/controls/OrbitControls.js';

const geometries = [
  new THREE.BoxBufferGeometry(200, 200, 200, 2, 2, 2),
  new THREE.CircleBufferGeometry(200, 32),
  new THREE.CylinderBufferGeometry(75, 75, 200, 8, 8),
  new THREE.IcosahedronBufferGeometry(100, 1),
  new THREE.OctahedronBufferGeometry(200, 0),
  new THREE.PlaneBufferGeometry(200, 200, 4, 4),
  new THREE.RingBufferGeometry(32, 64, 16),
  new THREE.SphereBufferGeometry(100, 12, 12),
  new THREE.TorusBufferGeometry(64, 16, 12, 12),
  new THREE.TorusKnotBufferGeometry(64, 16)
]

const options = {
  geometry: 0
}

const scene = new THREE.Scene();
scene.background = new THREE.Color(0x000000);

const camera = new THREE.PerspectiveCamera(65, innerWidth / innerHeight, 1, 1000);
camera.position.z = 500;

const mtl = new THREE.MeshBasicMaterial({ color: 0xfefefe, wireframe: true, opacity: .5 })

let gmt, mesh;
// 构建网格模型
const addMesh = () => {
  if (mesh !== undefined) {
    scene.remove(mesh);
    gmt.dispose();
  }

  gmt = geometries[options.geometry];
  // 缩放几何体到统一尺寸
  gmt.computeBoundingSphere(); // 重新计算边界球，更新 Geometry.boundingSphere 属性值

  const scaleFactor = 160 / gmt.boundingSphere.radius;
  gmt.scale(scaleFactor, scaleFactor, scaleFactor);

  mesh = new THREE.Mesh(gmt, mtl);
  scene.add(mesh);

  // 顶点法线辅助线
  const vertexNormalHelper = new THREE.VertexNormalsHelper(mesh, 10);
  mesh.add(vertexNormalHelper);
}
addMesh();

const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(devicePixelRatio);
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);

new OrbitControls(camera, renderer.domElement);

// GUI
const gui = new GUI({ width: 350 });
gui.add(options, 'geometry', {
  BoxBufferGeometry: 0,
  CircleBufferGeometry: 1,
  CylinderBufferGeometry: 2,
  IcosahedronBufferGeometry: 3,
  OctahedronBufferGeometry: 4,
  PlaneBufferGeometry: 5,
  RingBufferGeometry: 6,
  SphereBufferGeometry: 7,
  TorusBufferGeometry: 8,
  TorusKnotBufferGeometry: 9
}).onChange(() => {
  addMesh();
})

const render = () => {
  renderer.render(scene, camera);
}

const animate = () => {
  requestAnimationFrame(animate);

  render();
}
animate();

const handleWindowResize = () => {
  camera.aspect(innerWidth, innerHeight);
  camera.updateProjectionMatrix();

  renderer.setSize(innerWidth, innerHeight);
}

window.addEventListener('resize', handleWindowResize);
